package com.tide.crm.service.impl;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import com.tide.crm.dao.WeChatTokenDao;
import com.tide.crm.model.WeChatToken;
import com.tide.crm.service.WeChatService;
import com.tide.crm.utils.CreateIdUtils;
import com.tide.crm.utils.HttpClientUtils;
import com.tide.crm.utils.JsonMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;



@Service("weChatService")
public class WeChatServiceImpl implements WeChatService {

	@Value("${Wx.appId}")
    private  String appID ;//这里是AppId,我放到配置文件中了,也可以在这里写,直接定义全局变量,下面的开发者密码一样
    @Value("${Wx.appSecret}")
    private String appSecret;
    @Value("${Wx.url}")
    private String url;
    @Value("${Wx.QRCodeUrl}")
    private String qrCodeUrl;
    
    @Resource(name="weChatTokenDao")
    private WeChatTokenDao weChatTokenDao;
	
    @Transactional
	@Override
	public void saveWeChatAccessToken() throws Exception {
		// TODO Auto-generated method stub
		String getUrl = url+"&appid="+appID+"&secret="+appSecret;
		String resultStr = HttpClientUtils.doGet(getUrl, null);
		WeChatToken accessToken = JsonMapper.fromJson(resultStr, WeChatToken.class);
		accessToken.setId(CreateIdUtils.getEntityId());
		//System.out.println(":"+accessToken.getAccess_token()+":"+accessToken.getExpires_in()+":"+accessToken.getErrcode()+":"+accessToken.getErrmsg());
		weChatTokenDao.deleteAllToken();
		weChatTokenDao.saveToken(accessToken);
	}


	@Override
	public void updateWeChatToken() {
		// TODO Auto-generated method stub
		System.out.println("测试Token 获取");
	}

	@Override
	public void saveWeChatQRCode(Long businessId)  {
		// TODO Auto-generated method stub
		String token = null;
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("scene", "from=qrcode&id="+businessId);
		params.put("page", "pages/merchant/merchant"); //位置
        params.put("width", 430);
		//获取Token
		List<WeChatToken> tokenList = weChatTokenDao.getWeChatToken();
		if(!tokenList.isEmpty()) {
			WeChatToken wechatToken = tokenList.get(0);
			token = wechatToken.getAccessToken();
		}else {
			token = "";
		}
		String getUrl = qrCodeUrl+"?access_token="+token;
		
		try {
			HttpClientUtils.doPost(getUrl, params);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

       
	}
}
